//
//  MyCommentsViewController.m
//  GolfFriend
//
//  Created by Vescky on 14-5-12.
//  Copyright (c) 2014年 vescky.org. All rights reserved.
//

#import "MyCommentsViewController.h"
#import "AppDelegate.h"
#import "MyCommentCell.h"
#import "AppsEngine.h"
#import "UserSession.h"
#import "SVProgressHUD.h"
#import "JSON.h"
#import "CircleDetailViewController.h"
#import "CacheDaoForCircleContent.h"

@interface MyCommentsViewController ()<UITableViewDataSource,UITableViewDelegate> {
    NSMutableArray *commentList;
    MyCommentCell *sampleCell;
    NSString *currentIndex;
}
@end

@implementation MyCommentsViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    [self setTitle:@"我的评论"];
    [super customBackButton];
    [self.navigationController.navigationBar setHidden:NO];
    commentList = [[NSMutableArray alloc] init];
    
    [self initView];
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    if (ShowToolbarInWindow) {
        [APP_DELEGATE setToolbarHidden:NO];
        [self.navigationItem setHidesBackButton:YES animated:NO];
    }
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Private
- (void)initView {
    CGRect tbRect = tbView.frame;
    if (iPhone5) {
        tbRect.size.height = 454.f;
    }
    else {
        tbRect.size.height = 366.f;
    }
    if (!ShowToolbarInWindow) {
        tbRect.size.height = tbRect.size.height + 50;
    }
    
    [tbView setFrame:tbRect];
    tbView.separatorColor = [UIColor clearColor];
    currentIndex = Initial_index;
    
    //加载缓存的评论
    NSArray *cmArr = [[[UserSession shareUserSession] getHistoryComments] JSONValue];
    if (cmArr) {
        commentList = [NSMutableArray arrayWithArray:cmArr];
    }
    
    [self getDataFromServer];
}

//获取Cell的高度
- (float)getCellHeightWithContent:(NSDictionary*)_dict {
    if (!sampleCell) {
        sampleCell = [[[NSBundle mainBundle] loadNibNamed:@"MyCommentCell" owner:self options:nil] objectAtIndex:0];
    }
    return [sampleCell getCellHeightWithData:_dict];
}

- (void)getDataFromServer {
    NSMutableDictionary *params = [[NSMutableDictionary alloc] initWithObjectsAndKeys:[[UserSession shareUserSession] getUserId],@"userId",currentIndex,@"currentId", nil];
    //网上请求数据
    [[AppsEngine shareAppsEngine] submitRequest:@"gfGetHistoryComments" param:params onCompletion:^(id jsonResponse) {
        if ([jsonResponse objectForKey:@"status"] && [[jsonResponse objectForKey:@"status"] isEqualToString:@"success"]) {
            NSLog(@"刷新成功");
            [tbView setHidden:NO];
            if ([currentIndex isEqualToString:Initial_index]) {
                [SVProgressHUD showSuccessWithStatus:@"刷新成功"];
                [commentList removeAllObjects];
            }
            
            NSMutableArray *arr1 = [jsonResponse objectForKey:@"content"];
            if ([arr1 respondsToSelector:@selector(count)] && [arr1 count] > 0) {
                [[UserSession shareUserSession] saveHistoryComments:[arr1 JSONFragment]];//缓存
                [commentList addObjectsFromArray:arr1];
                NSDictionary *newestItem = [commentList lastObject];
                if ([newestItem objectForKey:@"id"]) {
                    currentIndex = [newestItem objectForKey:@"id"];
                }
                [tbView reloadData];
            }
            else {
                if ([commentList count] < 1) {
                    //无内容
                    [tbView setHidden:YES];
                    label1.text = @"暂时没有人评论您!";
                }
                else {
                    if (![currentIndex isEqualToString:Initial_index]) {
                        [SVProgressHUD showSuccessWithStatus:@"没有更多评论了!"];
                    }
                }
            }
        }
        else {
            if ([commentList count] < 1) {
                //无内容
                [tbView setHidden:YES];
                label1.text = @"暂时没有人评论您!";
            }
            else {
                if (![currentIndex isEqualToString:Initial_index]) {
                    [SVProgressHUD showSuccessWithStatus:@"没有更多评论了!"];
                }
            }
        }
        [super endRefreshing];
    } onError:^(NSError *error) {
        NSLog(@"联网失败");
        [super endRefreshing];
        if ([commentList count] < 1) {
            //无内容
            [tbView setHidden:YES];
            label1.text = @"暂时没有人评论您!";
        }
        else {
            if (![currentIndex isEqualToString:Initial_index]) {
                [SVProgressHUD showSuccessWithStatus:@"没有更多评论了!"];
            }
        }
    } method:@"GET"];
}

#pragma mark - over write
- (void)refreshData {
    currentIndex = Initial_index;
    [self getDataFromServer];
}

- (void)loadMoreData {
    [self getDataFromServer];
}


#pragma mark - UITableViewDelegate
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return [commentList count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *CellIdentifier = @"MyCommentCell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    
    if(!cell){
        cell = [[[NSBundle mainBundle] loadNibNamed:@"MyCommentCell" owner:self options:nil] objectAtIndex:0];
    }
    
    if([cell respondsToSelector:@selector(setCellDataInfo:)]){
        [cell performSelector:@selector(setCellDataInfo:) withObject:[commentList objectAtIndex:indexPath.row]];
    }
    
    [cell setTag:indexPath.row];
    
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return [self getCellHeightWithContent:[commentList objectAtIndex:indexPath.row]];
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    NSDictionary *dict = [commentList objectAtIndex:indexPath.row];
    CircleContentVO *cVo = [[CacheDaoForCircleContent shareCacheDaoForCircleContent] getCacheDataWithArticleId:[dict objectForKey:@"articleId"]];
    CircleDetailViewController *cDetailView = [[CircleDetailViewController alloc] init];
    [cDetailView setContentVO:cVo];
    [self.navigationController pushViewController:cDetailView animated:YES];
}

- (void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(NSIndexPath *)indexPath {
    NSLog(@"MyCommentCell selected:%d",indexPath.row);
}


@end
